const express = require('express');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

const app = express();
const config = {
    chatHistoryFile: path.join(__dirname, 'chat_history.txt'),
    port: 8888,
    host: '0.0.0.0'
};

// Middleware
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// Chat history management
const chatHistory = {
    read: () => {
        if (!fs.existsSync(config.chatHistoryFile)) return [];

        const content = fs.readFileSync(config.chatHistoryFile, 'utf8').trim();
        if (content.length === 0) return [];

        const lines = content.split('\n');
        const history = [];

        for (const line of lines) {
            if (line.startsWith('用户: ')) {
                history.push({ role: '用户', content: line.substring(3) });
            } else if (line.startsWith('瑠璃: ')) {
                history.push({ role: '瑠璃', content: line.substring(3) });
            }
        }

        return history;
    },

    save: (userMessage, assistantResponse) => {
        const userLine = `用户: ${userMessage}`;
        const assistantLine = `瑠璃: ${assistantResponse.trim()}`;

        let content;
        try {
            const stats = fs.statSync(config.chatHistoryFile);
            content = stats.size > 0 ? `\n${userLine}\n${assistantLine}` : `${userLine}\n${assistantLine}`;
        } catch (error) {
            // 文件不存在，直接创建新内容
            content = `${userLine}\n${assistantLine}`;
        }

        fs.appendFileSync(config.chatHistoryFile, content, 'utf8');
    },

    clear: () => {
        if (fs.existsSync(config.chatHistoryFile)) {
            fs.unlinkSync(config.chatHistoryFile);
        }
    }
};

// AI model interaction
const aiModel = {
    getResponse: (prompt, signal) => {
        return new Promise((resolve, reject) => {
            // 依赖本地可执行程序 'iflow'
            const child = spawn('iflow', ['-p', prompt]);

            let response = '';
            let errorOutput = '';

            // 监听中止信号
            if (signal) {
                const handleAbort = () => {
                    child.kill('SIGTERM');
                    reject(new Error('Request aborted'));
                };

                signal.addEventListener('abort', handleAbort);

                child.on('close', () => {
                    signal.removeEventListener('abort', handleAbort);
                });
            }

            child.stdout.on('data', data => response += data.toString());
            child.stderr.on('data', data => errorOutput += data.toString());

            child.on('close', code => {
                if (code !== 0) {
                    reject(new Error(`Command exited with code ${code}: ${errorOutput}`));
                } else {
                    resolve(response.trim());
                }
            });
        });
    }
};

// Routes
app.post('/chat', async (req, res) => {
    try {
        const { message } = req.body;

        if (message.toLowerCase().trim() === 'clean') {
            chatHistory.clear();
            console.log('Chat history cleared via chat command.');
            res.json({ response: '聊天记录已清除。' });
            return;
        }

        const history = chatHistory.read();

        const historyText = history.map(entry =>
            `${entry.role}: ${entry.content}`
        ).join('\n');

        // 构建包含全部历史记录的长字符串 Prompt
        const prompt = history.length > 0
            ? `${historyText}\n以上为之前的聊天记录。\n消息: ${message}\n瑠璃:`
            : `消息: ${message}\n瑠璃:`;

        const response = await aiModel.getResponse(prompt, req.signal);
        chatHistory.save(message, response);

        res.json({ response });
    } catch (error) {
        // 如果是请求被中止，不返回错误状态
        if (error.message === 'Request aborted') {
            console.log('Chat request aborted by client');
            return;
        }

        console.error('Chat error:', error);
        res.status(500).json({ error: 'Failed to get AI response' });
    }
});

app.post('/clean', (req, res) => {
    try {
        chatHistory.clear();
        console.log('Chat history cleared via /clean endpoint.');
        res.json({ success: true, message: 'History cleared.' });
    } catch (error) {
        console.error('Clean error:', error);
        res.status(500).json({ error: 'Failed to clean chat history' });
    }
});

// Start server
app.listen(config.port, config.host, () => {
    console.log(`Server listening at http://${config.host}:${config.port}`);
});
